<template>
  <div class="chat-container">
    <!-- 顶部导航栏 -->
    <el-header class="chat-header">
      <div class="header-content">
        <div class="logo">

          <span>DeepSeek Chat</span>
        </div>
        <div class="header-actions">
          <el-button type="success" icon="el-icon-refresh" @click="resetConversation">新对话</el-button>

        </div>
      </div>
    </el-header>

    <!-- 主聊天区域 -->
    <el-main class="chat-main">
      <div class="message-container" ref="messageContainer">
        <!-- 欢迎消息 -->
        <div class="welcome-message" v-if="messages.length === 0">
          <h2>欢迎使用 DeepSeek Chat</h2>
          <p>我是您的AI助手，可以回答各种问题、帮助创作和提供建议</p>
          <div class="quick-questions">
            <el-button
              v-for="(question, index) in quickQuestions"
              :key="index"
              round
              @click="sendQuickQuestion(question)"
            >
              {{ question }}
            </el-button>
          </div>
        </div>

        <!-- 消息列表 -->
        <div
          v-for="(message, index) in messages"
          :key="index"
          class="message-item"
          :class="{'user-message': message.role === 'user', 'ai-message': message.role === 'assistant'}"
        >
          <div class="message-avatar">
            <img
              v-if="message.role === 'user'"
              src="../../assets/images/user.jpeg"
              alt="User"
            >
            <img
              v-else
              src="../../assets/images/bot.jpeg"
              alt="AI"
            >
          </div>
          <div class="message-content">
            <div class="message-text" v-html="formatMessage(message.content)"></div>
            <div class="message-actions">
              <el-button
                v-if="message.role === 'assistant'"
                type="text"
                icon="el-icon-copy-document"
                size="mini"
                @click="copyToClipboard(message.content)"
              >
                复制
              </el-button>
              <el-button
                type="text"
                icon="el-icon-thumb"
                size="mini"
                @click="rateMessage(index, 'like')"
                :class="{active: message.rating === 'like'}"
              >
                {{ message.likes || 0 }}
              </el-button>
              <el-button
                type="text"
                icon="el-icon-thumb"
                size="mini"
                @click="rateMessage(index, 'dislike')"
                :class="{active: message.rating === 'dislike'}"
              >
                {{ message.dislikes || 0 }}
              </el-button>
              <span class="message-time">{{ formatTime(message.timestamp) }}</span>
            </div>
          </div>
        </div>

        <!-- 加载指示器 -->
        <div class="loading-indicator" v-if="isLoading">

          <span>AI正在思考...</span>
        </div>
      </div>

    </el-main>

    <!-- 输入区域 -->
    <el-footer class="chat-footer">
      <div class="input-container">
        <el-input
          type="textarea"
          :rows="2"
          :autosize="{ minRows: 2, maxRows: 6 }"
          placeholder="输入您的问题..."
          v-model="inputMessage"
          @keyup.enter.native="sendMessage"
          :disabled="isLoading"
          ref="inputArea"
        >
        </el-input>
        <div class="input-actions">
          <el-button
            type="primary"
            :loading="isLoading"
            @click="sendMessage"
            :disabled="!inputMessage.trim()"
          >
            发送
          </el-button>
        </div>
      </div>
      <div class="footer-notice">
        <span>DeepSeek Chat 可能会产生不准确的信息，请谨慎验证</span>
      </div>
    </el-footer>

  </div>
</template>

<script>

import { marked } from 'marked'
import DOMPurify from 'dompurify'

export default {
  name: 'ChatPage',
  data() {
    return {
      buffer: "",
      messages: [],//聊天信息
      inputMessage: '马云在哪个公司上班？',//输入框内容
      isLoading: false,//Ai是否正在加载和发送按钮状态
      showSettings: false, //设置面板,没有使用
      quickQuestions: [ //快捷问题
        "如何学习Vue.js?",
        "写一封辞职信模板",
        "推荐几个Python学习资源",
        "解释一下量子计算的基本概念"
      ],
      responseLength: 3,
      enableWebSearch: false
    }
  },
  methods: {

    async sendMessage() {//发送信息
      if (!this.inputMessage.trim() || this.isLoading) return

      //构建用户问题的对象
      const userMessage = {
        role: 'user',
        content: this.inputMessage,
        timestamp: new Date()
      }
      //添加用户聊天信息
      this.messages.push(userMessage)
      //清空输入框
      //this.inputMessage = ''
      //设置发送按钮是禁止和 AI加载状态为true
      this.isLoading = true

      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom()
      })
      const self = this;
          try {
                    // 清空之前的缓冲区
                    this.buffer = "";

                   // 发起流式请求
                   const response = await fetch(`http://localhost:8000/robot/?info=${encodeURIComponent(this.inputMessage)}`);

                    // 获取流式读取器
                    const reader = response.body.getReader();
                    const decoder = new TextDecoder("utf-8");

                    while (true) {
                        // 读取数据
                        const { done, value } = await reader.read();
                        // 流式结束，跳出循环
                        if (done) break;
                        // 解码数据
                        let data = decoder.decode(value, { stream: true })
                        // 更新缓冲区
                        this.buffer += data;

                    }

                    const aiMessage = {
                        role: 'assistant',//表示AI回复
                        content: self.buffer,// 内容
                      timestamp: new Date()
                     }
            //添加AI回复到聊天记录里
            self.messages.push(aiMessage);
            //设置发送按钮是允许和 AI加载状态为false
            self.isLoading = false;
                } catch (error) {
                    console.error("流式数据接收失败:", error);
                }

    },
    sendQuickQuestion(question) {
      this.inputMessage = question
      this.sendMessage()
    },
    resetConversation() {
      this.$confirm('确定要开始新的对话吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        this.messages = []
      })
    },
    scrollToBottom() {
      const container = this.$refs.messageContainer
      container.scrollTop = container.scrollHeight
    },
    formatMessage(content) {
      // 使用marked解析markdown并净化HTML
      return DOMPurify.sanitize(marked.parse(content || ''))
    },
    formatTime(timestamp) {
      return new Date(timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
    },
    copyToClipboard(text) {
      navigator.clipboard.writeText(text).then(() => {
        this.$message.success('已复制到剪贴板')
      })
    },
    rateMessage(index, type) {
      const message = this.messages[index]

      if (type === 'like') {
        if (message.rating === 'like') {
          message.rating = null
          message.likes = (message.likes || 1) - 1
        } else {
          if (message.rating === 'dislike') {
            message.dislikes = (message.dislikes || 1) - 1
          }
          message.rating = 'like'
          message.likes = (message.likes || 0) + 1
        }
      } else {
        if (message.rating === 'dislike') {
          message.rating = null
          message.dislikes = (message.dislikes || 1) - 1
        } else {
          if (message.rating === 'like') {
            message.likes = (message.likes || 1) - 1
          }
          message.rating = 'dislike'
          message.dislikes = (message.dislikes || 0) + 1
        }
      }
    },
    focusInput() {
      this.$refs.inputArea.focus()
    }
  },
  mounted() {
    this.focusInput()
  }
}
</script>

<style scoped>
.chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.chat-header {
  background-color: #ffffff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  padding: 0 20px;
}

.header-content {
  height: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

.logo {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.logo img {
  margin-right: 10px;
  border-radius: 50%;
}

.header-actions .el-button {
  margin-left: 10px;
}

.chat-main {
  flex: 1;
  padding: 0;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.message-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  max-width: 900px;
  margin: 0 auto;
  width: 100%;
}

.welcome-message {
  text-align: center;
  padding: 40px 0;
  color: #606266;
}

.welcome-message h2 {
  font-size: 24px;
  margin-bottom: 16px;
}

.welcome-message p {
  font-size: 16px;
  margin-bottom: 24px;
}

.quick-questions {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 10px;
  margin-top: 20px;
}

.quick-questions .el-button {
  margin: 0 5px 5px 0;
}

.message-item {
  display: flex;
  margin-bottom: 20px;
}

.message-avatar {
  margin-right: 15px;
}

.message-avatar img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.message-content {
  flex: 1;
  max-width: calc(100% - 55px);
}

.message-text {
  padding: 12px 16px;
  border-radius: 8px;
  line-height: 1.6;
  word-wrap: break-word;
}

.user-message .message-text {
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
}

.ai-message .message-text {
  background-color: #ffffff;
  border: 1px solid #ebeef5;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.message-actions {
  margin-top: 8px;
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #909399;
}

.message-actions .el-button {
  padding: 0;
  margin-right: 10px;
  color: #909399;
}

.message-actions .el-button.active {
  color: #409eff;
}

.message-time {
  margin-left: auto;
}

.loading-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 15px;
  color: #909399;
}

.loading-indicator .el-icon {
  margin-right: 8px;
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.chat-footer {
  padding: 0;
  background-color: #ffffff;
  box-shadow: 0 -1px 3px rgba(0, 0, 0, 0.1);
}

.input-container {
  max-width: 700px;
  margin: 0 auto;
  padding: 15px;
  width: 100%;
}

.input-tools {
  margin-bottom: 5px;
}

.input-tools .el-button {
  padding: 0;
  margin-right: 10px;
}

.input-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.footer-notice {
  text-align: center;
  padding: 10px;
  font-size: 12px;
  color: #909399;
  border-top: 1px solid #ebeef5;
}

/* Markdown内容样式 */
.message-text :deep(pre) {
  background-color: #f6f8fa;
  padding: 12px;
  border-radius: 6px;
  overflow-x: auto;
}

.message-text :deep(code) {
  background-color: #f6f8fa;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: monospace;
}

.message-text :deep(blockquote) {
  border-left: 3px solid #dfe2e5;
  color: #6a737d;
  padding-left: 12px;
  margin-left: 0;
}

.message-text :deep(ul),
.message-text :deep(ol) {
  padding-left: 20px;
}

.message-text :deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin: 12px 0;
}

.message-text :deep(th),
.message-text :deep(td) {
  border: 1px solid #dfe2e5;
  padding: 6px 13px;
}

.message-text :deep(th) {
  background-color: #f6f8fa;
}
</style>
